package com.litchishell.jdbcdemo.service;

import com.litchishell.jdbcdemo.connection.ConnectionUtils;

import java.lang.reflect.Field;
import java.sql.*;

/**
 * @Author: Jiangxx
 * @Date: 2022/04/07
 * @Description:
 */
public class JdbcService {

    /**
     * 通用增删改查
     * @param sql
     * @param params
     */
    public void changeDataMethode(String sql, Object... params) {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = ConnectionUtils.getConnectionMethod5();
            ps = conn.prepareStatement(sql);

            // 填充sql占位符
            for (int i = 0; i < params.length; i++) {
                ps.setObject(i+1, params[i]);
            }

            // 执行
            ps.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            ConnectionUtils.closeConnection(conn);
        }
    }

    /**
     * 通用的针对于不同表的查询:返回一个对象
     * @param clazz
     * @param sql
     * @param args
     * @return
     */
    public Object getInstance(Class clazz, String sql, Object... args) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        Object result = null;
        try {
            // 1.获取数据库连接
            conn = ConnectionUtils.getConnectionMethod5();
            // 2.预编译sql语句，得到PreparedStatement对象
            ps = conn.prepareStatement(sql);
            // 3.填充占位符
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }
            // 4.执行executeQuery(),得到结果集：
            rs = ps.executeQuery();
            // 5.得到结果集的元数据：ResultSetMetaData
            ResultSetMetaData rsmd = rs.getMetaData();
            // 6.1通过ResultSetMetaData得到columnCount,columnLabel；通过ResultSet得到列值
            int columnCount = rsmd.getColumnCount();
            if (rs.next()) {
                result = clazz.newInstance();
                for (int i = 0; i < columnCount; i++) {
                    // 遍历每一个列
                    // 获取列值
                    Object columnVal = rs.getObject(i + 1);
                    // 获取列的别名:列的别名，使用类的属性名充当
                    String columnLabel = rsmd.getColumnLabel(i + 1);
                    // 6.2使用反射，给对象的相应属性赋值
                    Field field = clazz.getDeclaredField(columnLabel);
                    field.setAccessible(true);
                    field.set(result, columnVal);
                }
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 7.关闭资源
            ConnectionUtils.closeConnection(conn);
        }
        return result;
    }
}
